package com.bdqn.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bdqn.pojo.SmbmsRole;
import com.bdqn.pojo.SmbmsUser;
import com.bdqn.pojo.User;
import com.bdqn.pojo.UserCondition;
import com.bdqn.serice.SmbmsRoleService;
import com.bdqn.serice.SmbmsUserService;
import com.bdqn.serice.impl.SmbmsRoleServiceImpl;
import com.bdqn.utils.Constants;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author www
 * @Description: 控制器
 * @date 2020-06-08 8:44
 */

@Controller
public class UserCintroller {
    @Resource
    private SmbmsUserService smbmsUserService;
    @Resource
    private SmbmsRoleService smbmsRoleService;
    //查询
    @RequestMapping(value = "/queryUser.do")
    public String queryUser(User user, Model model) throws Exception {
        //用户名
        String queeyname = user.getQueryname();
        //角色
        Integer queryRole = org.springframework.util.StringUtils.isEmpty(user.getQueryUserRole()) ? 0
                : Integer.valueOf(user.getQueryUserRole());
        //当前页面
        String pageIndex = user.getPageIndex();
        //判断当前页面是否为空
        Integer pageIndexInteger = StringUtils.isEmpty(pageIndex) ? 1
                : Integer.valueOf(pageIndex);
        //获取当前用户信息
        List<SmbmsUser> userList = smbmsUserService.getUserList(queeyname, queryRole, pageIndexInteger, Constants.pageSize);
        //获得用户总记录数
        int userCount = smbmsUserService.getUserCount(queeyname, queryRole);
        //计算总页数
        int totalPage = userCount % Constants.pageSize == 0 ? userCount / Constants.pageSize
                : (userCount / Constants.pageSize) + 1;
        //封装数据
        model.addAttribute("userList", userList);
        model.addAttribute("currentPageNo", pageIndexInteger);
        model.addAttribute("totalCount", userCount);
        model.addAttribute("totalPageCount", totalPage);
        //查询条件回复
        model.addAttribute("queryUserName", queeyname);
        //用户角色回显 queryUserRole
        model.addAttribute("queryUserRole", queryRole);
        model.addAttribute("roleList", smbmsRoleService.getRoleList());
        return "userlist";
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping(value = "/DelUser.do")
    @ResponseBody
    public String DelUser(@RequestParam(value = "uid") Long id) {
        System.out.println("进入删除");
        Map<String, String> map = new HashMap<>();
        if (id <= 0) {
            map.put("delResult", "notexist");
        } else {
            int i = smbmsUserService.deleteUserById(id);
            if (i > 0) {
                map.put("delResult", "true");
            } else {
                map.put("delResult", "false");
            }
        }
        String jsonString = JSONObject.toJSONString(map);
        return jsonString;
    }

    //新增跳转
    @RequestMapping(value = "/toAddUser.do")
    public String toAddUser() {
        return "useradd";
    }

    //新增
    @RequestMapping(value = "/AddUser.do")
    public String AddUser(UserCondition user, HttpSession session) throws ParseException {
        SmbmsUser smbmsUser = new SmbmsUser();
        BeanUtils.copyProperties(user, smbmsUser);
        smbmsUser.setBirthday(new SimpleDateFormat("yyyy-mm-dd").parse(user.getBirthday()));
        System.out.println("新增"+smbmsUser.getBirthday());
        SmbmsUser loginUser = (SmbmsUser) session.getAttribute(Constants.USER_SESSION);
        if (loginUser == null) {
            return "redirect:logout.do";
        }
        smbmsUser.setCreatedBy(loginUser.getId());
        smbmsUser.setCreationDate(new Date());
        int i = smbmsUserService.insertOrUpdateSelective(smbmsUser);
        if (i > 0) {
            return "redirect:queryUser.do";
        }
        return "useradd";
    }

    //查看
    @RequestMapping(value = "/getUserById/{url}/{userid}")
    public String getUserById(@PathVariable(value = "url") String url, @PathVariable(value = "userid") String id, Model model) {
        SmbmsUser userById = smbmsUserService.getUserById(id);
        User user = new User();
        BeanUtils.copyProperties(userById, user);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        System.out.println("原本的" + userById.getBirthday());
        String date = simpleDateFormat.format(userById.getBirthday());
//        System.out.println("date===" + date);
        user.setBirthday(date);
//        System.out.println("转换的" + user.getBirthday());
        model.addAttribute("user", user);
        return url;
    }

    //修改用户
    @RequestMapping(value = "/UpdateUser.do")
    public String UpdateUser(UserCondition user, HttpSession session) throws ParseException {
        System.out.println("页面值："+user.toString());


        SmbmsUser smbmsUser = new SmbmsUser();
        BeanUtils.copyProperties(user, smbmsUser);
        //String 转 Date
        smbmsUser.setBirthday(new SimpleDateFormat("yyyy-mm-dd").parse(user.getBirthday()));
        System.out.println("转换后的" + smbmsUser.getBirthday());
        System.out.println(smbmsUser.toString());
        SmbmsUser loginUser = (SmbmsUser) session.getAttribute(Constants.USER_SESSION);
        if (loginUser == null) {
            return "redirect:logout.do";
        }
        smbmsUser.setModifyBy(loginUser.getId());
        smbmsUser.setModifyDate(new Date());
        int update = smbmsUserService.updateByPrimaryKeySelective(smbmsUser);
        System.out.println("返回值"+update);
        if (update > 0) {
            return "redirect:queryUser.do";
        }
        return "usermodify";
    }

    //角色初始化
    @GetMapping(value = "/getRoleList.do")
    @ResponseBody
    public String getRoleList() throws Exception {
        List<SmbmsRole> roleList = smbmsRoleService.getRoleList();
        String jsonString = JSONObject.toJSONString(roleList);
        return jsonString;
    }

    //判断用户是否存在
    @GetMapping(value = "/UserByName.do")
    @ResponseBody
    public String UserByName(@RequestParam(value = "userCode") String userCode) {
        //判断用户账号是否可用
        Map<String, Object> resultMap = new HashMap<>(16);
        if (userCode.isEmpty()) {
            resultMap.put("userCode", "exist");
        } else {
            SmbmsUser user = smbmsUserService.selectUserCodeExist(userCode);
            if (null != user) {
                resultMap.put("userCode", "exist");
            } else {
                resultMap.put("userCode", "notexist");
            }
        }
        String jsonString = JSONObject.toJSONString(resultMap);
        return jsonString;
    }

    //跳转密码修改页面
    @RequestMapping(value = "/pwdModify.do")
    public String pwdModify() {
        return "pwdmodify";
    }

    //判断当前用户密码
    @GetMapping(value = "/getPwdById.do")
    @ResponseBody
    public String getPwdById(@RequestParam(value = "oldpassword") String pwd, HttpSession session) {
        SmbmsUser loginUser = (SmbmsUser) session.getAttribute(Constants.USER_SESSION);
        Map<String, String> resultMap = new HashMap<String, String>(16);
        if (null == loginUser) {
            //session过期
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isEmpty(pwd)) {
            //旧密码输入为空
            resultMap.put("result", "error");
        } else {
            //获得用户登录的密码
            String sessionPwd = loginUser.getUserPassword();
            //判断输入的密码是否与登录密码一致
            if (pwd.equals(sessionPwd)) {
                resultMap.put("result", "true");
            } else {
                //旧密码输入不正确
                resultMap.put("result", "false");
            }
        }
        String jsonString = JSONArray.toJSONString(resultMap);
        return jsonString;
    }

    //修改密码
    @RequestMapping(value = "/UpdatePwdById.do")
    public String UpdatePwdById(@RequestParam(value = "newpassword") String pwd, HttpSession session) {

        SmbmsUser loginUser = (SmbmsUser) session.getAttribute(Constants.USER_SESSION);

        int update = smbmsUserService.updatePwd(loginUser.getId(), pwd);
        if (update > 0) {
            return "login";
        } else {
            return "pwdmodify";
        }
    }
}
